package ionio.cscw.game;

import java.util.List;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

public class Database  {
	
	private DatastoreService datastore=DatastoreServiceFactory.getDatastoreService();
	
	public long getNewId() {
		Key key=KeyFactory.createKey("IdCounter",1);
		Entity newId;
		try{
			newId=datastore.get(key);
			long id=(Long)newId.getProperty("counter");
			id++;
			newId.setProperty("counter", id);
			datastore.put(newId);
			return id;
		}catch(EntityNotFoundException ex) {
			newId=new Entity(key);
			newId.setProperty("counter", 0);
			datastore.put(newId);
			return 0;	
		}
	}
	
	private Entity getVideo(int video_id) {
		Key key=KeyFactory.createKey(null,"Video",video_id);
		Entity video;
		try{
			video=datastore.get(key);
		}catch(EntityNotFoundException ex) {
			video=new Entity(key);
			video.setProperty("name", "video-"+video_id);
			datastore.put(video);
		}
		return video;
	}

	public void storeData(long id, long timestamp, String word, int vId) {
		Entity record = new Entity("record",getVideo(vId).getKey());
		record.setProperty("id", id);
		record.setProperty("timestamp", timestamp);
		record.setProperty("word", word);
		datastore.put(record);	
	}
	
	public void storeScore(long id, String name, long score, int vId) {
		Entity scores = new Entity("scores",getVideo(vId).getKey());
		scores.setProperty("id", id);
		scores.setProperty("name", name);
		scores.setProperty("score", score);
		datastore.put(scores);
	}
	
	
	public List<Entity> getBestScores(int vId,int limit) {
		Query q = new Query("scores",getVideo(vId).getKey());
		q.addSort("score", Query.SortDirection.DESCENDING);
		PreparedQuery pq = datastore.prepare(q);
		return pq.asList(FetchOptions.Builder.withLimit(limit));
	}

}
